﻿using System;
using System.Collections.Generic;
using System.Text;
using Tauren.Business.Entity.Global;
using Tauren.Business.Entity.Model;
using Tauren.Business.Entity.Output;
using Tauren.Business.Infrastructure.Globals;
using Dapper;
using Dapper.Contrib.Extensions;
using System.Linq;

namespace Tauren.Business.DLL.ButtonDLL
{
    public class ButtonsBusiness : Base.BaseDLL, IButtonsBusiness
    {
        public ButtonsBusiness(IConnectionDLLBase _dLLBase) : base(_dLLBase)
        {
        }

        public bool Edit(Buttons data) => this.dbConnection.Update(data);

        public List<ButtonsTable> Get(long AutoID) =>
            this.dbConnection.Query<ButtonsTable>($"SELECT a.autoId,a.btnid,a.icon,a.type,a.size,a.`value` `code`,a.shape,a.isuseflow,a.location,b.`language`,b.`value`,a.creator,a.creatdate,a.modifier,a.modifdate,a.sequence   FROM buttons a LEFT JOIN buttonres b on a.btnid=b.btnid WHERE a.autoId=@AutoId", new Buttons() { AutoId = AutoID }).ToList();

        public long Add(Buttons data) => this.dbConnection.Insert(data);

        public bool Add(List<ButtonRes> resoucesRes)
        {
            if (resoucesRes.Any())
            {
                this.dbConnection.Execute($"DELETE FROM buttonres WHERE btnid = {resoucesRes.FirstOrDefault().BtnId};");
                return this.dbConnection.Insert(resoucesRes) >= 0;
            }
            return true;
        }

        public List<PageButtonsTable> Pages(QueryModel queryModel, out long Total)
        {
            Total = 0;
            string where = "";
            if (!string.IsNullOrEmpty(queryModel.KeyWord))
            {
                where += $"   where (a.value LIKE '%{queryModel.KeyWord}%' OR b.value LIKE '%{queryModel.KeyWord}%' )";
            }
            if (string.IsNullOrEmpty(queryModel.SortField))
            {
                queryModel.SortField = "a.AutoId";
                queryModel.IsAsc = false;
            }
            else
            {
                queryModel.SortField = queryModel.SortField.ToLower().Replace("dic_", "").Replace("dic", "").Trim();
            }
            if (queryModel.paramters.Any())
            {
                if (string.IsNullOrEmpty(queryModel.KeyWord)) where = " where  "; else where += " AND ";
                where = where + string.Join(" AND ", queryModel.paramters.Select(o => $"{(o.Label == "code" ? "a.value" : o.Label == "value" ? "b.value" : o.Label)}  like '%{o.Value}%'"));
            }
            string asc = queryModel.IsAsc ? "ASC" : "DESC";
            queryModel.Page = queryModel.Page == 0 ? 1 : queryModel.Page;
            StringBuilder sql = new StringBuilder();
            sql.Append(@$"select count(a.AutoId) as cnt
                        FROM  buttons a LEFT JOIN buttonres b ON a.btnid=b.btnid 
                        AND b.`language` = '{this.Global.Language}'  {where} ;");
            sql.Append(@$"SELECT a.autoId,a.btnid,a.icon,a.type,a.size,a.`value` `code`,a.shape,a.isuseflow,a.location,b.`language`,b.`value`,a.creator,a.creatdate,a.modifier,a.modifdate,a.sequence  
                        FROM buttons a LEFT JOIN buttonres b ON a.btnid=b.btnid 
                        AND b.`language` = '{this.Global.Language}'  
                        {where}  ORDER BY {queryModel.SortField} {asc} LIMIT {(queryModel.Page - 1) * queryModel.PageSize},{queryModel.PageSize} ;");
            using (var reader = dbConnection.QueryMultiple(sql.ToString()))
            {
                Total = reader.ReadFirstOrDefault<int>();
                List<PageButtonsTable> pageModules = reader.Read<PageButtonsTable>().ToList();
                long RowNo = ((queryModel.Page == 0 ? 1 : queryModel.Page) - 1) * queryModel.PageSize + 1;
                pageModules.ForEach(o =>
                {
                    o.RowNo = RowNo;
                    RowNo++;
                });
                return pageModules;
            }
        }

        public bool PhysicallyDeleted(long AutoID) => this.dbConnection.Execute($"delete from buttons where autoid ={AutoID}; delete  from buttonres where btnid in(select btnid from buttons where autoid ={AutoID});") >= 0;

        public Buttons Singe(long AutoID) => this.dbConnection.Get<Buttons>(AutoID);
    }
}
